﻿using System;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;


namespace PublicFunction
{
    /// <summary>
    /// 
    /// </summary>
    public class MyEncrypt1
    {
        /// <summary>
        /// 公钥
        /// </summary>
        public static string PublicKey { get; private set; }
        /// <summary>
        /// 私钥
        /// </summary>
        public static string PrivateKey { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        //private static void GetKey()
        //{
        //    //RSA密钥对的构造器  
        //    RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();

        //    //RSA密钥构造器的参数  
        //    RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
        //        Org.BouncyCastle.Math.BigInteger.ValueOf(3),
        //        new Org.BouncyCastle.Security.SecureRandom(),
        //        1024,   //密钥长度  
        //        25);
        //    //用参数初始化密钥构造器  
        //    keyGenerator.Init(param);
        //    //产生密钥对  
        //    AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
        //    //获取公钥和密钥  
        //    AsymmetricKeyParameter publicKey = keyPair.Public;
        //    AsymmetricKeyParameter privateKey = keyPair.Private;

        //    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
        //    PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

        //    Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

        //    byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
        //    Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
        //    byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");

        //    PublicKey = Convert.ToBase64String(publicInfoByte);
        //    PrivateKey = Convert.ToBase64String(privateInfoByte);
        //}

        /// <summary>
        /// 
        /// </summary>
        public static void GetConstkey()
        {
            PublicKey = "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCWcVaSPqic/lUneEWcAQkRStc9grwuOaL" +
                "Zs5LfeXmvr1CjinxkR8FY771e/XmmoRDNhLBsQ9n0zpfnNeYBRefuFoKna2NntwBoB1bTC0Bv+Z1kYjLHu7ym+xt9U5tH07L0/4eW" +
                "DnSk21yO3JZVo8lwoak0lM5CXSR24SPtGsBcLQIBAw==";
            PrivateKey = "MIICdAIBADANBgkqhkiG9w0BAQEFAASCAl4wggJaAgEAAoGBAJZxVpI+qJz+VSd4RZwBCRFK1z2CvC45otmz" +
                "kt95ea+vUKOKfGRHwVjvvV79eaahEM2EsGxD2fTOl+c15gFF5+4WgqdrY2e3AGgHVtMLQG/5nWRiMse7vKb7G31Tm0fTsvT/h5YOdK" +
                "TbXI7cllWjyXChqTSUzkJdJHbhI+0awFwtAgEDAoGAGRLjwwpxb3+42+lg71WBguHOikB0sl7weZ3tz+mUR/KNcJcUu2FK5" +
                "Cf05So+8RrYIkDIEgtO/iJupoj7quD7/MJMw4OJCGG9xtMPiiPsxuCrCfHrD9zVu07/Xt285MUhZM6Gipo+LLKwoB12S89Scrcnu" +
                "ncs6VkHERIcxE2S/SsCQQDK2crWjlHS7WuFIbLnGGiW6yj/kllCj4wX0vBGt/oz/Dnb8eGljobnEofYUyvmCwYay40JBYxx3ax" +
                "jy15wC0dBAkEAvdxHf57jmaBTj9fjTJteHq//tx4PTCq3CUxT2nXxAO5eTG50y3ERxCZGU31i4c+6O+9IwLs91RxkEKv02U" +
                "Ml7QJBAIc73I8Ji+HznQNrzJoQRbnyG1UMO4G1CA/h9YR6ps1S0T1L68O0We9hr+WMx+6yBBHdCLCuXaE+cu0yPvVc2" +
                "isCQH6S2lUUl7vAN7U6l4hnlBR1VSS+tN1xz1uIN+b5S1X0Pt2e+IegtoLELuJTl0E1JtKfhdXSKTi9mAsdTeYsw/MCQAYr" +
                "NxvXR847iSUzbApv3OofUHBoJXA3hV2B67LxFnqMnV8SMNwHHNVvTbcp/JsuzJmEVa8TRmX64ma1eXtNk7g=";
        }

        //private static AsymmetricKeyParameter GetPublicKeyParameter(string s)
        //{
        //    s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
        //    byte[] publicInfoByte = Convert.FromBase64String(s);
        //    Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取，从本地导入   
        //    AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
        //    return pubKey;
        //}

        private static AsymmetricKeyParameter GetPrivateKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] privateInfoByte = Convert.FromBase64String(s);
            // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取，从本地导入   
            // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
            return priKey;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        //public static string EncryptByPrivateKey(string s)
        //{
        //    //非对称加密算法，加解密用  
        //    IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());

        //    //加密  
        //    try
        //    {
        //        engine.Init(true, GetPublicKeyParameter(PublicKey));
        //        byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
        //        var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
        //        return Convert.ToBase64String(ResultData);
        //        //Console.WriteLine("密文（base64编码）:" + Convert.ToBase64String(testData) + Environment.NewLine);
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.Message;
        //    }
        //}

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string DecryptByPublicKey(string s)
        {

            try//解密  
            {
                s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "+");
                //非对称加密算法，加解密用  
                IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());

                engine.Init(false, GetPrivateKeyParameter(PrivateKey));
                byte[] byteData = Convert.FromBase64String(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return System.Text.Encoding.UTF8.GetString(ResultData);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
